import { defineStore } from 'pinia'
import { payService, PAYMENT_STATUS, REFUND_STATUS } from '@/services/pay.js'

export const usePayStore = defineStore('pay', {
  state: () => ({
    // 支付记录
    paymentRecords: [],
    paymentRecordsLoading: false,
    paymentRecordsTotal: 0,
    
    // 退款记录
    refundRecords: [],
    refundRecordsLoading: false,
    refundRecordsTotal: 0,
    
    // 支付统计
    paymentStatistics: {},
    paymentStatisticsLoading: false,
    
    // 支付配置
    paymentConfig: {},
    paymentConfigLoading: false,
    
    // 支付方式
    paymentMethods: [],
    paymentMethodsLoading: false,
    
    // 支付限额
    paymentLimits: {},
    paymentLimitsLoading: false,
    
    // 最近支付记录
    recentPayments: [],
    recentPaymentsLoading: false,
    
    // 支付日志
    paymentLogs: [],
    paymentLogsLoading: false,
    
    // 当前支付状态
    currentPayment: null,
    paymentPolling: false,
    
    // 错误信息
    paymentError: null
  }),

  getters: {
    // 获取支付记录总数
    getPaymentRecordsCount: (state) => state.paymentRecords.length,
    
    // 获取退款记录总数
    getRefundRecordsCount: (state) => state.refundRecords.length,
    
    // 获取成功支付记录
    getSuccessPayments: (state) => 
      state.paymentRecords.filter(record => record.paymentStatus === PAYMENT_STATUS.SUCCESS),
    
    // 获取失败支付记录
    getFailedPayments: (state) => 
      state.paymentRecords.filter(record => record.paymentStatus === PAYMENT_STATUS.FAILED),
    
    // 获取待支付记录
    getPendingPayments: (state) => 
      state.paymentRecords.filter(record => record.paymentStatus === PAYMENT_STATUS.PENDING),
    
    // 获取成功退款记录
    getSuccessRefunds: (state) => 
      state.refundRecords.filter(record => record.refundStatus === REFUND_STATUS.SUCCESS),
    
    // 获取处理中退款记录
    getProcessingRefunds: (state) => 
      state.refundRecords.filter(record => record.refundStatus === REFUND_STATUS.PROCESSING),
    
    // 计算总支付金额
    getTotalPaymentAmount: (state) => 
      state.paymentRecords
        .filter(record => record.paymentStatus === PAYMENT_STATUS.SUCCESS)
        .reduce((total, record) => total + parseFloat(record.paymentAmount), 0),
    
    // 计算总退款金额
    getTotalRefundAmount: (state) => 
      state.refundRecords
        .filter(record => record.refundStatus === REFUND_STATUS.SUCCESS)
        .reduce((total, record) => total + parseFloat(record.refundAmount), 0),
    
    // 计算支付成功率
    getPaymentSuccessRate: (state) => {
      const total = state.paymentRecords.length
      const success = state.paymentRecords.filter(record => record.paymentStatus === PAYMENT_STATUS.SUCCESS).length
      return total > 0 ? Math.round((success / total) * 100) : 0
    },
    
    // 计算退款成功率
    getRefundSuccessRate: (state) => {
      const total = state.refundRecords.length
      const success = state.refundRecords.filter(record => record.refundStatus === REFUND_STATUS.SUCCESS).length
      return total > 0 ? Math.round((success / total) * 100) : 0
    },
    
    // 获取支付方式统计
    getPaymentMethodStats: (state) => {
      const stats = {}
      state.paymentRecords.forEach(record => {
        const method = record.paymentMethod
        if (!stats[method]) {
          stats[method] = { count: 0, amount: 0 }
        }
        stats[method].count++
        stats[method].amount += parseFloat(record.paymentAmount)
      })
      return stats
    },
    
    // 检查是否有支付错误
    hasPaymentError: (state) => !!state.paymentError,
    
    // 获取当前支付状态
    getCurrentPaymentStatus: (state) => state.currentPayment?.paymentStatus
  },

  actions: {
    // 加载支付记录
    async loadPaymentRecords(params = {}) {
      this.paymentRecordsLoading = true
      this.paymentError = null
      
      try {
        const res = await payService.getPaymentRecords(params)
        
        if (res.success) {
          this.paymentRecords = res.data.list || []
          this.paymentRecordsTotal = res.data.total || 0
        } else {
          this.paymentError = res.message || '获取支付记录失败'
        }
      } catch (error) {
        console.error('加载支付记录失败:', error)
        this.paymentError = '网络错误'
      } finally {
        this.paymentRecordsLoading = false
      }
    },

    // 加载退款记录
    async loadRefundRecords(params = {}) {
      this.refundRecordsLoading = true
      this.paymentError = null
      
      try {
        const res = await payService.getRefundRecords(params)
        
        if (res.success) {
          this.refundRecords = res.data.list || []
          this.refundRecordsTotal = res.data.total || 0
        } else {
          this.paymentError = res.message || '获取退款记录失败'
        }
      } catch (error) {
        console.error('加载退款记录失败:', error)
        this.paymentError = '网络错误'
      } finally {
        this.refundRecordsLoading = false
      }
    },

    // 加载支付统计
    async loadPaymentStatistics(params = {}) {
      this.paymentStatisticsLoading = true
      this.paymentError = null
      
      try {
        const res = await payService.getPaymentStatistics(params)
        
        if (res.success) {
          this.paymentStatistics = res.data.statistics || {}
          this.recentPayments = res.data.recentPayments || []
        } else {
          this.paymentError = res.message || '获取支付统计失败'
        }
      } catch (error) {
        console.error('加载支付统计失败:', error)
        this.paymentError = '网络错误'
      } finally {
        this.paymentStatisticsLoading = false
      }
    },

    // 加载支付配置
    async loadPaymentConfig() {
      this.paymentConfigLoading = true
      this.paymentError = null
      
      try {
        const res = await payService.getPaymentConfig()
        
        if (res.success) {
          this.paymentConfig = res.data
        } else {
          this.paymentError = res.message || '获取支付配置失败'
        }
      } catch (error) {
        console.error('加载支付配置失败:', error)
        this.paymentError = '网络错误'
      } finally {
        this.paymentConfigLoading = false
      }
    },

    // 加载支付方式
    async loadPaymentMethods() {
      this.paymentMethodsLoading = true
      this.paymentError = null
      
      try {
        const res = await payService.getPaymentMethods()
        
        if (res.success) {
          this.paymentMethods = res.data || []
        } else {
          this.paymentError = res.message || '获取支付方式失败'
        }
      } catch (error) {
        console.error('加载支付方式失败:', error)
        this.paymentError = '网络错误'
      } finally {
        this.paymentMethodsLoading = false
      }
    },

    // 加载支付限额
    async loadPaymentLimits() {
      this.paymentLimitsLoading = true
      this.paymentError = null
      
      try {
        const res = await payService.getPaymentLimits()
        
        if (res.success) {
          this.paymentLimits = res.data || {}
        } else {
          this.paymentError = res.message || '获取支付限额失败'
        }
      } catch (error) {
        console.error('加载支付限额失败:', error)
        this.paymentError = '网络错误'
      } finally {
        this.paymentLimitsLoading = false
      }
    },

    // 加载支付日志
    async loadPaymentLogs(params = {}) {
      this.paymentLogsLoading = true
      this.paymentError = null
      
      try {
        const res = await payService.getPaymentLogs(params)
        
        if (res.success) {
          this.paymentLogs = res.data.list || []
        } else {
          this.paymentError = res.message || '获取支付日志失败'
        }
      } catch (error) {
        console.error('加载支付日志失败:', error)
        this.paymentError = '网络错误'
      } finally {
        this.paymentLogsLoading = false
      }
    },

    // 创建支付订单
    async createPayment(orderId) {
      this.paymentError = null
      
      try {
        const res = await payService.createPayment(orderId)
        
        if (res.success) {
          this.currentPayment = res.data
          return res.data
        } else {
          this.paymentError = res.message || '创建支付订单失败'
          return null
        }
      } catch (error) {
        console.error('创建支付订单失败:', error)
        this.paymentError = '网络错误'
        return null
      }
    },

    // 执行支付
    async executePayment(orderId, paymentData) {
      this.paymentError = null
      this.paymentPolling = true
      
      try {
        const result = await payService.completePayment(orderId, paymentData)
        
        if (result.success) {
          // 支付成功，刷新支付记录
          await this.loadPaymentRecords()
          return result.data
        } else {
          this.paymentError = result.message || '支付失败'
          return null
        }
      } catch (error) {
        console.error('执行支付失败:', error)
        this.paymentError = error.message || '支付失败'
        return null
      } finally {
        this.paymentPolling = false
        this.currentPayment = null
      }
    },

    // 申请退款
    async applyRefund(params) {
      this.paymentError = null
      
      try {
        const res = await payService.applyRefund(params)
        
        if (res.success) {
          // 退款申请成功，刷新退款记录
          await this.loadRefundRecords()
          return res.data
        } else {
          this.paymentError = res.message || '申请退款失败'
          return null
        }
      } catch (error) {
        console.error('申请退款失败:', error)
        this.paymentError = '网络错误'
        return null
      }
    },

    // 查询支付状态
    async queryPaymentStatus(orderId) {
      try {
        const res = await payService.queryPayment(orderId)
        
        if (res.success) {
          this.currentPayment = res.data
          return res.data
        } else {
          this.paymentError = res.message || '查询支付状态失败'
          return null
        }
      } catch (error) {
        console.error('查询支付状态失败:', error)
        this.paymentError = '网络错误'
        return null
      }
    },

    // 轮询支付状态
    async pollPaymentStatus(orderId, maxAttempts = 10) {
      this.paymentPolling = true
      
      try {
        const result = await payService.pollPaymentStatus(orderId, maxAttempts)
        this.currentPayment = result
        return result
      } catch (error) {
        this.paymentError = error.message || '支付状态查询失败'
        throw error
      } finally {
        this.paymentPolling = false
      }
    },

    // 记录支付日志
    async logPayment(params) {
      try {
        await payService.logPayment(params)
      } catch (error) {
        console.error('记录支付日志失败:', error)
      }
    },

    // 清除错误信息
    clearError() {
      this.paymentError = null
    },

    // 重置支付状态
    resetPaymentState() {
      this.currentPayment = null
      this.paymentPolling = false
      this.paymentError = null
    },

    // 刷新所有数据
    async refreshAllData() {
      await Promise.all([
        this.loadPaymentRecords(),
        this.loadRefundRecords(),
        this.loadPaymentStatistics(),
        this.loadPaymentConfig(),
        this.loadPaymentMethods(),
        this.loadPaymentLimits()
      ])
    },

    // 添加支付记录到列表
    addPaymentRecord(record) {
      this.paymentRecords.unshift(record)
      this.paymentRecordsTotal++
    },

    // 更新支付记录
    updatePaymentRecord(paymentId, updates) {
      const index = this.paymentRecords.findIndex(record => record.paymentId === paymentId)
      if (index !== -1) {
        this.paymentRecords[index] = { ...this.paymentRecords[index], ...updates }
      }
    },

    // 添加退款记录到列表
    addRefundRecord(record) {
      this.refundRecords.unshift(record)
      this.refundRecordsTotal++
    },

    // 更新退款记录
    updateRefundRecord(refundId, updates) {
      const index = this.refundRecords.findIndex(record => record.refundId === refundId)
      if (index !== -1) {
        this.refundRecords[index] = { ...this.refundRecords[index], ...updates }
      }
    }
  }
}) 